package org.raymond.iworks.study.basic.designpattern.prototype.deepclone;

import lombok.Getter;
import lombok.Setter;

import java.io.*;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Setter
@Getter
public class DeepProtoType implements Serializable, Cloneable {
    private String name;
    private DeepCloneableTarget target;

    public DeepProtoType() {
    }

    @Override
    protected Object clone() {
        Object deep = null;
        try {
            deep = super.clone();
        } catch (CloneNotSupportedException e) {
            System.err.println(e.getMessage());
        }
        return deep;
    }

    // 深拷贝-方式1
    public Object deepClone1() {
        Object deep = null;
        try {
            deep = super.clone();
            DeepProtoType deepProtoType = (DeepProtoType)deep;
            deepProtoType.target = (DeepCloneableTarget)target.clone();
        } catch (CloneNotSupportedException e) {
            System.err.println(e.getMessage());
        }
        return deep;
    }

    // 深拷贝-方式2
    public Object deepClone2(){
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        Object deep = null;
        try{
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            deep = ois.readObject();
        }catch (Exception e){
            System.err.println(e.getMessage());
        }finally {
            try{
                if(bos!=null) bos.close();
                if(oos!=null) oos.close();
                if(bis!=null) bis.close();
                if(ois!=null) ois.close();
            }catch(Exception e){
                System.err.println(e.getMessage());
            }
        }
        return deep;
    }
}
